import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LocaleProvider with ChangeNotifier {

  Locale _locale;

  LocaleProvider(){
    getLocale();
  }

  void changeLocale(Locale locale) {
    _locale = locale;
    setLocale(_locale);
    notifyListeners();
  }

  Locale locale() {
    return _locale;
  }

  void getLocale() async {
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    String language = preferences.getString("language") ?? "zh_CN";
    List<String> ss = language.split("_");
    Locale locale;
    if (ss.length == 1) {
      locale = new Locale(ss[0]);
    } else if (ss.length == 2) {
      locale = new Locale(ss[0], ss[1]);
    }
    changeLocale(locale);
  }

  void setLocale(Locale locale) async {
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    await preferences.setString("language", locale.toString());
  }
}
